<template>
	<view class="container">
		<navView navTitle="客户详情" backgroundColor="#008efe" titleColor="#fff" :isBack="true"></navView>
		<view class="userinfo">
			<view class="flex">
				<view class="left">
					<view class="avatar-name">
						<image class="avatar" src="https://hfd.bjlzkj.com/static/user/ava.png" mode=""></image>
						<view class="name">
							{{ coustomer.name || '客户名称' }}
						</view>
					</view>
					<view class="status">
						状态：<text>{{ coustomer.follow }}</text>
					</view>
					<view class="yijian">
						重要程度：<view class="list">
							<image src="https://hfd.bjlzkj.com/static/user/xing.png" v-for="item in star" mode="">
							</image>
						</view>
					</view>
				</view>
				<view class="over">
					<view class="charts-box">
						<qiun-data-charts type="radar" :opts="opts" :chartData="chartData" />
					</view>
				</view>
			</view>
			<view class="texts">
				基本信息：{{ coustomer.content || '暂无基本信息' }}
			</view>
			<view class="texts">
				地址：{{ coustomer.address || '暂无地址' }}
			</view>
		</view>
		<view class="chengbox">
			<view class="title">
				<view class="left">
					<view class="tiao"></view>
					<view class="name">
						成交项目
					</view>
				</view>
				<view class="right">
					更多
					<uni-icons type="right" size="30rpx" color="#C3C3C3"></uni-icons>
				</view>
			</view>
			<view class="project-list">
				<view class="project-card" v-for="(project, index) in coustomer.completedProjects" :key="index">
					<!-- 项目名称和状态 -->
					<view class="project-header">
						<text>{{ project.name }}</text>
					</view>
					<!-- 负责人信息 -->
					<view class="project-detail">
						<view class="userbox" @tap.stop="showPhone('sale', index, 'completed')">
							销售：{{ project.sale.name }}
							<view class="phone-wrapper" v-if="completedShowPhone[index]">
								<image class="image" src="https://hfd.bjlzkj.com/static/list/phone-icon.png" mode="">
								</image>
								<text>{{ project.sale.mobile }}</text>
							</view>
						</view>
						<view class="userbox" @tap.stop="showPhone('technology', index, 'completed')">
							技术：{{ project.technology.name }}
							<view class="phone-wrapper" v-if="completedShowTechnology[index]">
								<image class="image" src="https://hfd.bjlzkj.com/static/list/phone-icon.png" mode="">
								</image>
								<text>{{ project.technology.mobile }}</text>
							</view>
						</view>
						<view class="userbox" @tap.stop="showPhone('finance', index, 'completed')">
							财务：{{ project.finance.name }}
							<view class="phone-wrapper" v-if="completedShowFinance[index]">
								<image class="image" src="https://hfd.bjlzkj.com/static/list/phone-icon.png" mode="">
								</image>
								<text>{{ project.finance.mobile }}</text>
							</view>
						</view>
						<view class="userbox" @tap.stop="showPhone('executive', index, 'completed')">
							行政：{{ project.executive.name }}
							<view class="phone-wrapper" v-if="completedShowExecutive[index]">
								<image class="image" src="https://hfd.bjlzkj.com/static/list/phone-icon.png" mode="">
								</image>
								<text>{{ project.executive.mobile }}</text>
							</view>
						</view>
					</view>
					<!-- 功能标签栏 -->
					<view class="tab-bar">
						<text class="tab-item"
							@tap="$navTo('/subpkg/contract/contractDetail/contractDetail')">合同详情</text>
						<!-- <text class="tab-item">项目成果</text>
						<text class="tab-item">合同付款</text>
						<text class="tab-item">开票情况</text> -->
					</view>
				</view>
			</view>
		</view>
		<view class="chengbox">
			<view class="title">
				<view class="left">
					<view class="tiao"></view>
					<view class="name">
						意向项目
					</view>
				</view>
				<view class="right" @click="moreproject">
					更多
					<uni-icons type="right" size="30rpx" color="#C3C3C3"></uni-icons>
				</view>
			</view>
			<view class="project-list">
				<view class="project-card" v-for="(project, index) in coustomer.pendingProjects" :key="index">
					<!-- 项目名称和状态 -->
					<view class="project-header">
						<text>{{ project.name }}</text>
					</view>					
				</view>
			</view>

		</view>
		<view class="chengbox">
			<view class="title">
				<view class="left">
					<view class="tiao"></view>
					<view class="name">
						跟进记录
					</view>
				</view>
				<view class="right">
					更多
					<uni-icons type="right" size="30rpx" color="#C3C3C3"></uni-icons>
				</view>
			</view>
			<view class="times" v-for="(record, index) in coustomer.followUpRecords" :key="index">
				<view class="span">
					跟进时间：{{ record.follow_time || '暂无时间' }}
				</view>
				<view class="span">
					基本内容：{{ record.content || '暂无内容' }}
				</view>
			</view>
		</view>
		<!-- 项目选择弹窗 -->
		<uni-popup v-if="showProjectPopup == true" type="bottom" :is-mask-click="true" @maskClick="closePopup"
			@close="closePopup">
			<view class="popup-container" style="z-index: 9999;position: fixed;bottom: 0;left: 0;right: 0;">
				<!-- 确保搜索框存在 -->
				<view class="search-box" style="padding:20rpx;background:#fff;position:sticky;top:0;z-index:999">
					<uni-search-bar placeholder="输入项目名称搜索" v-model="searchKeyword" @confirm="handleSearch"
						@clear="handleSearch" style="width:100%" />
				</view>

				<scroll-view scroll-y :style="{ height: `calc(70vh - 160rpx)` }" class="project-scroll"
					@scrolltolower="loadMore">
					<view v-for="(item, index) in projectList" :key="index" class="project-item"
						@click="selectProject(index)">
						{{ item.name }}
					</view>

					<view class="loading-text">
						<uni-load-more :status="currentPage < totalPages ? 'loading' : 'noMore'" :content-text="{
							contentdown: '上拉显示更多',
							contentrefresh: '正在加载...',
							contentnomore: '没有更多了'
						}" color="#999" />
					</view>
				</scroll-view>

				<view class="popup-close" @click="closePopup">
					<uni-icons type="close" size="30" color="#999"></uni-icons>
				</view>
			</view>
		</uni-popup>
	</view>
</template>

<script>
import uniSearchBar from '@/uni_modules/uni-search-bar/components/uni-search-bar/uni-search-bar'
import uniLoadMore from '@/uni_modules/uni-load-more/components/uni-load-more/uni-load-more'

export default {
	components: {
		uniSearchBar,
		uniLoadMore,
	},
	data() {
		return {
			chartData: {},
			coustomer: {},
			completedShowPhone: [],  // 成交项目电话状态
			completedShowTechnology: [],
			completedShowFinance: [],
			completedShowExecutive: [],
			pendingShowPhone: [],     // 意向项目电话状态
			pendingShowTechnology: [],
			pendingShowFinance: [],
			pendingShowExecutive: [],
			id: 0,
			//您可以通过修改 config-ucharts.js 文件中下标为 ['radar'] 的节点来配置全局默认参数，如都是默认参数，此处可以不传 opts 。实际应用过程中 opts 只需传入与全局默认参数中不一致的【某一个属性】即可实现同类型的图表显示不同的样式，达到页面简洁的需求。
			opts: {
				color: ["#1890FF", "#91CB74", "#FAC858", "#EE6666", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
					"#ea7ccc"
				],
				padding: [5, 5, 5, 5],
				dataLabel: false,
				enableScroll: false,
				legend: {
					show: true,
					position: "right",
					lineHeight: 25
				},
				extra: {
					radar: {
						gridType: "radar",
						gridColor: "#CCCCCC",
						gridCount: 3,
						opacity: 0.2,
						max: 10,
						labelShow: true,
						border: true
					}
				}
			},
			projects: [{}],
			chatData: {},//客户星级
			star: 1,
			currentPage: 1,
			totalPages: 1,
			searchKeyword: '',
			projectList: [],
			showProjectPopup: false, // 新增弹窗控制变量
		}
	},
	onLoad(opetion) {
		this.id = opetion.id;
		this.getServerData();
	},
	methods: {
		closePopup() {
			this.showProjectPopup = false;
			this.searchKeyword = '';
			this.currentPage = 1;
		},
		moreproject() {
			this.showProjectPopup = true;
			this.currentPage = 1;
			this.loadProjects();
		},
		async loadProjects() {
			uni.showLoading({ title: '加载中...' });  // 新增加载提示
			try {
				const res = await this.$request('/addons/qingdong/project/getAllProjectList', 'GET', {
					id: this.id,
					page: this.currentPage,
					pageSize: 10,
					keyword: this.searchKeyword
				});

				if (this.currentPage === 1) {
					this.projectList = res.data.data || [];
				} else {
					this.projectList = [...this.projectList, ...res.data.data];
				}

				this.totalPages = res.data.totalPages;

			} catch (e) {
				console.error(e);
			} finally {
				uni.hideLoading();  // 新增：关闭加载提示
			}
		},
		handleSearch() {
			this.currentPage = 1;
			this.loadProjects();
		},
		loadMore() {
			if (this.currentPage < this.totalPages) {
				this.currentPage++;
				this.loadProjects();
			}
		},
		selectProject(index) {
			const selected = this.projectList[index];
			this.$request('/addons/qingdong/project/addProject', 'POST', {
				id: selected.id,
				customer_id: this.coustomer.id
			}).then(res => {
				uni.showToast({
					title: '添加成功',
					icon: 'success'
				})
				this.getServerData();
			})
			this.closePopup();
		},
		getAllProject() {
			this.$request('/addons/qingdong/project/getAllProjectList', 'GET', {
				id: this.id
			}).then(res => {
				console.log(res.data.data, 'project')
				if (res.data?.length > 0) {
					// 转换数据结构为 actionSheet 需要的格式
					const projectList = res.data.data.map(item => ({
						text: item.name,
						...item
					}))
				}
			})
		},
		getServerData() {
			this.$request('/addons/qingdong/customer/customerDetail', 'GET', {
				id: this.id
			}).then(res => {
				this.coustomer = res.data
				this.star = res.data.level
				this.chatData = res.data.projectStats
				//动态计算最大值
				const maxValue = Math.max(...(this.chatData?.series?.data || []), 5); // 至少显示5

				console.log(maxValue, 'maxValue');
				this.$set(this.opts.extra.radar, 'max', maxValue + 2); // 加2留出余量
			})
			//模拟从服务器获取数据时的延时
			setTimeout(() => {
				// 生成基础数据
				let res = {
					categories: this.chatData?.categories?.split(',') || [],
					series: [{
						name: this.chatData?.series?.name || '项目数量',
						data: (this.chatData?.series?.data || '').split(',').map(Number) || []
					}]
				};

				// 添加默认数据逻辑
				if (res.categories.length === 0 || res.series[0].data.every(v => v === 0)) {
					res = {
						categories: ["沟通", "需求", "方案", "报价", "服务", "进度"],
						series: [{
							name: '默认数据',
							data: [1, 1, 1, 1, 1, 1] // 全1保证基础雷达图形状
						}]
					};
					this.opts.extra.radar.max = 3; // 调整默认最大值
				}

				this.chartData = JSON.parse(JSON.stringify(res));
			}, 500);

		},
		showPhone(role, index, type) {
			const stateMap = {
				completed: {
					sale: this.completedShowPhone,
					technology: this.completedShowTechnology,
					finance: this.completedShowFinance,
					executive: this.completedShowExecutive
				},
				pending: {
					sale: this.pendingShowPhone,
					technology: this.pendingShowTechnology,
					finance: this.pendingShowFinance,
					executive: this.pendingShowExecutive
				}
			};

			// 重置该类型下所有状态数组
			Object.values(stateMap[type]).forEach(arr => arr.fill(false));

			// 设置当前点击项状态
			const targetArr = stateMap[type][role];
			targetArr.splice(index, 1, true);
		}
	}
}
</script>

<style lang="scss">
.container {
	padding: 20rpx;
}

.popup-container {
	background: #fff;
	height: 70vh;
	padding: 20rpx;
	/* 移除 position: relative */
	/* 添加以下样式 */
	box-shadow: 0 -10rpx 30rpx rgba(0, 0, 0, 0.1);
	border-radius: 20rpx 20rpx 0 0;

	.uni-searchbar {
		width: 100% !important;
	}

	/* 添加以下样式确保搜索框可见 */
	.search-box {
		padding: 20rpx;
		position: sticky;
		top: 0;
		z-index: 1;
	}


	.project-scroll {
		height: calc(70vh - 180rpx);

		.project-item {
			padding: 20rpx;
			border-bottom: 1rpx solid #eee;

			&:active {
				background-color: #f5f5f5;
			}
		}

		.loading-text {
			padding: 20rpx;

			/* 可根据需要调整组件间距 */
			.uni-load-more {
				transform: scale(0.9);
			}
		}
	}

	.popup-close {
		position: absolute;
		right: 20rpx;
		top: 20rpx;
		z-index: 9999;
	}
}

.userinfo {
	width: 100%;
	padding: 20rpx;
	box-sizing: border-box;
	background: #FFFFFF;
	box-shadow: 0rpx 6rpx 16rpx 1rpx rgba(114, 110, 255, 0.11);
	border-radius: 20rpx 20rpx 20rpx 20rpx;

	.flex {
		display: flex;
		align-items: center;
		position: relative;

		.left {
			width: 50%;

			.avatar-name {
				display: flex;
				align-items: center;
				margin-bottom: 50rpx;
				margin-top: 50rpx;

				.avatar {
					width: 81rpx;
					height: 81rpx;
					margin-right: 20rpx;
				}

				.name {
					font-weight: bold;
					font-size: 30rpx;
					color: #333333;
				}
			}

			.status {
				font-weight: 400;
				font-size: 26rpx;
				color: #333333;

				text {
					color: #008EFE;
				}
			}

			.yijian {
				font-weight: 400;
				font-size: 26rpx;
				color: #333333;
				display: flex;
				align-items: center;
				margin: 10rpx 0;

				.list {
					display: flex;
					align-items: center;

					image {
						width: 34rpx;
						height: 34rpx;
						margin: 0 5rpx;
					}
				}
			}
		}

		.over {
			width: 400rpx;
			height: 400rpx;
			overflow: hidden;
			position: absolute;
			right: -30rpx;
			top: -70rpx;

			.charts-box {
				width: 600rpx;
				height: 600rpx;
				position: absolute;
				left: -40rpx;
				top: -100rpx;
			}
		}
	}

	.texts {
		font-weight: 400;
		font-size: 26rpx;
		color: #333333;
		margin-top: 10rpx;
	}
}

.chengbox {
	width: 100%;
	background-color: #fff;
	box-shadow: 0rpx 1rpx 6rpx 1rpx rgba(97, 97, 97, 0.25);
	margin: 30rpx 0;
	border-radius: 8rpx;

	.title {
		width: 100%;
		padding: 20rpx 10rpx;
		box-sizing: border-box;
		display: flex;
		align-items: center;
		justify-content: space-between;
		border-bottom: 1rpx solid #E9E9E9;

		.left {
			display: flex;
			align-items: center;

			.tiao {
				width: 9rpx;
				height: 30rpx;
				background: #008EFE;
				border-radius: 3rpx 3rpx 3rpx 3rpx;
				margin-right: 20rpx;
			}

			.name {
				font-weight: 400;
				font-size: 30rpx;
				color: #333333;
			}
		}

		.right {
			font-weight: 400;
			font-size: 24rpx;
			color: #B0B0B0;

			.uni-icons {
				margin-left: 10rpx;
			}
		}
	}

	.project-list {
		border-radius: 16rpx;

		.project-card:last-child {
			border: 0;
		}

		.project-card {
			overflow: hidden;
			margin-bottom: 20rpx;
			padding: 20rpx;
			margin: 20rpx 0;
			border-bottom: 1rpx solid #E9E9E9;

			.project-header {
				display: flex;
				align-items: center;
				margin-bottom: 10rpx;

				text {
					font-size: 32rpx;
					font-weight: bold;
				}
			}

			.project-detail {
				font-size: 28rpx;
				color: #333;
				margin-bottom: 20rpx;
				display: flex;
				align-items: center;

				.userbox {
					position: relative;
				}

				.phone-wrapper {
					position: absolute;
					bottom: -50rpx;
					left: 0;
					z-index: 10;
					display: flex;
					align-items: center;
					margin-top: 10rpx;
					background: #fff;
					box-shadow: 0 2rpx 6rpx 2rpx #c1c1c1;
					padding: 3rpx 5rpx;
					box-sizing: 10rpx;

					.image {
						width: 32rpx;
						height: 32rpx;
						margin-right: 10rpx;
					}
				}
			}

			.tab-bar {
				display: flex;
				justify-content: space-between;
				margin-bottom: 20rpx;

				.tab-item {
					width: 20%;
					text-align: center;
					padding: 8rpx 0;
					background-color: #e0f1ff;
					border-radius: 10rpx;
					color: #007aff;
					font-size: 24rpx;
				}
			}

			.service-evaluation {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-size: 24rpx;
				color: #E56C2B;
				background-color: #F5F5F5;
				padding: 10rpx 10rpx;
				box-sizing: border-box;
				border-radius: 10rpx;

				.right {
					width: 8rpx;
					height: 16rpx;
					margin-left: 20rpx;
				}
			}
		}
	}

	.times {
		width: 100%;
		border-bottom: 1rpx solid #E9E9E9;
		padding: 20rpx;
		box-sizing: border-box;

		.span {
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
			margin: 20rpx 0;
		}
	}
}
</style>